<!--
 * @Author: wangming
 * @Date: 2021-04-01 14:02:25
 * @LastEditors: wangming
 * @LastEditTime: 2022-07-12 16:22:03
 * @Description: file content
-->
<template>
  <div>
    <div class="ks-row-middle mb20 lh1">
      <div class="mr10 g3">事件设置</div>
      <i
        class="el-icon-circle-plus-outline iconcolor f20 poi"
        @click="addTag"
      ></i>
    </div>
    <div
      v-for="(i, index) in value.__highSetUp.events"
      :key="index"
      class="mb5"
    >
      <div v-show="i.children.length > 0">
        {{ i.label }}
      </div>
      <div
        class="ks-row-middle g6 mt5 codebg"
        v-for="(item, jdex) in i.children"
        :key="jdex"
      >
        <!--        添加自定义事件-->
        <template v-if="item.composeType !== 'logic'">
          <div class="ks-col">{{ item.eventName }}</div>
          <span
            v-if="item.composeType == 'custom'"
            class="iconfont icondaima mr10 poi"
            @click="openCode()"
          ></span>
          <span class="iconfont iconbianji mr10 poi" @click="edit(item)"></span>
          <el-popconfirm
            placement="top"
            title="确认删除当前事件吗"
            @confirm="remove(jdex, i.children)"
          >
            <span slot="reference" class="iconfont iconicon_shanchu poi"></span>
          </el-popconfirm>
        </template>
        <template v-else>
          <div class="ks-col">{{ item.eventName }}</div>
          <img
            src="@/assets/image/composer.svg"
            width="16"
            class="poi mr10"
            @click="openBlockEditor(item)"
          />
          <el-popconfirm
            placement="top"
            title="确认删除当前事件吗"
            @confirm="removeComposer(jdex, i.children, item)"
          >
            <span slot="reference" class="iconfont iconicon_shanchu poi"></span>
          </el-popconfirm>
        </template>
      </div>
    </div>
    <BlockEditor ref="BlockEditor"></BlockEditor>
  </div>
</template>

<script>
import { Message } from "element-ui";
import basicmixins from "../basicmixins";
import Module from "./addModule";
import { mapGetters } from "vuex";
import { Events } from "@/utils/Dynamic.js";
import eventTypeList, { ButtonEvents } from "./eventTypeList.js";
import BlockEditor from "@/components/blockly/BlockEditor";
import { uuid } from "@/utils/common.js";
import { desigconfig } from "@/pageConfig/index.js";
import MicroBlocklyEditor from "@/components/BlocklyEditor";

export default {
  name: "EventIndex",
  mixins: [basicmixins],
  computed: {
    ...mapGetters(["getFormData"]),
    eventTypeList() {
      if (this.value.tagName === "hlButton") {
        return ButtonEvents.filter(
          (i) => i.types.indexOf(this.value.buttnType) > -1
        );
      } else {
        return eventTypeList.filter(
          (i) => i.tagNames.indexOf(this.value.tagName) > -1
        );
      }
    },
  },
  components: {
    BlockEditor,
  },
  data() {
    return {
      uuid,
      desigconfig,
    };
  },
  mounted() {
    this.value.__highSetUp.events.forEach((i) => {
      // 兼容处理
      if (i.value === "click") {
        i.label = "点击事件";
      }
    });
  },
  methods: {
    openCode() {
      this.$monacoEditor.showEdit("javascript", this.getFormData);
      // const { js, css } = this.getFormData;
      // this.$monacoEditor.showEdit("javascript", { js, css }).then((res) => {
      //   this.getFormData.js = res.javascript;
      //   this.getFormData.css = res.css;
      // });
    },
    remove(index, list) {
      list.splice(index, 1);
    },
    removeComposer(index, list, event) {
      list.splice(index, 1);
      // 从全局删除逻辑编排
      const composerIndex = this.getFormData.composer?.findIndex(
        (item) => item.composerKey === event.composerKey
      );
      // this.getFormData.composer.splice(composerIndex, 1);
    },
    edit(item) {
      Module.editModule(item, this.eventTypeList).then((res) => {
        Object.assign(item, res);
        this.getFormData.js = Events.addFunctionJSON(
          this.getFormData.js,
          res?.eventName,
          res?.event?.options || []
        );
      });
    },
    addTag() {
      Module.addForm(this.eventTypeList).then((eventData) => {
        const { eventName, event, composeType, systemEvent } = eventData;
        if (composeType == "system") {
          this.addEvents(eventName, event, composeType, "", systemEvent);
        } else if (composeType !== "logic") {
          try {
            this.addEvents(eventName, event, composeType);
            // 全局添加js todo
            this.getFormData.js = Events.addFunctionJSON(
              this.getFormData.js,
              eventName,
              event.options || []
            );
          } catch (error) {
            console.log(error);
          }
          this.openCode();
        } else {
          const eventItem = eventData;
          const composerKey = this.handleAddComposerKey(eventItem);
          this.addEvents(eventName, event, composeType, composerKey);
          const data = {
            eventName,
            event,
            composerKey,
            componentId: this.value.key,
          };
          // // 全局添加逻辑编排
          if (!this.getFormData?.composer) this.getFormData.composer = [];

          // this.getFormData.composer.push(data);
          // this.openBlockEditor({ eventName, event, composeType, composerKey });

          // ** start 使用新版编排新增数据 since v2.7.1 **
          let funcParams = ["context", ...(event.options || [])];
          const defaultData = {
            ...data,
            funcName: composerKey,
            funcDesc: eventName,
            componentId: this.value.key,
            componentType: this.value.tagName,
            eventType: eventData?.event?.value,
            eventMethod: "BLOCKLY",
            funcParams: funcParams + "",
            _MicroApp: true,
          };
          this.getFormData.composer.push(defaultData);
          MicroBlocklyEditor.openForDesktop(defaultData);
          // ** end **
        }
      });
    },
    addEvents(
      eventName,
      event,
      composeType = "custom",
      composerKey = "",
      systemEvent = []
    ) {
      const isE = this.value.__highSetUp.events.find(
        (i) => i.value === event.value
      );
      if (isE) {
        this.value.__highSetUp.events.forEach((i) => {
          if (i.value == event.value) {
            i.children.push({
              eventName,
              event,
              composeType,
              composerKey,
              systemEvent,
            });
          }
        });
      } else {
        this.value.__highSetUp.events.push({
          value: event.value,
          label: event.label,
          children: [
            { eventName, event, composeType, composerKey, systemEvent },
          ],
        });
      }
    },
    // 添加逻辑编排的key
    handleAddComposerKey(eventItem) {
      // 获取组件的配置
      // 从组件的key中获取组件的类型
      const alias = this.value.key?.split("_")[0];
      const key = alias + "_" + eventItem?.event?.value + "_" + uuid(6);
      return key;
    },

    openBlockEditor(item) {
      const composerData = this.getFormData.composer?.find(
        (event) => event.composerKey === item.composerKey
      );

      if (!composerData) {
        Message.warning("未找到对应编排信息");
        return;
      }

      // ** start 编辑时判断编排版本 since v2.7.1 **
      if (composerData._MicroApp) {
        MicroBlocklyEditor.openForDesktop(composerData);
        return;
      }
      // ** end **

      const eventData = {
        ...item,
        eventXml: composerData.eventXml,
        eventJs: composerData.eventJs,
      };
      this.$refs.BlockEditor.open(eventData, this.value, (data) => {
        // 更新组件逻辑编排名称
        item.eventName = data.eventName;
        // 将变更之后的数据保存到全局
        composerData.eventName = data.eventName;
        composerData.eventXml = data.eventXml;
        composerData.eventJs = encodeURIComponent(data.eventJs);
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.codebg {
  background-color: #f3f9ff;
  padding: 2px 4px;
}
</style>
